package com.oreilly.ez.fileserver.service;


import com.oreilly.ez.fileserver.base.YmlConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class FileService {

    @Autowired
    private YmlConfig ymlConfig;



    public Resource loadFileAsResource(String fileName) throws MalformedURLException {

        Path filePath = Paths.get(ymlConfig.getUploadDir()).toAbsolutePath().normalize();

        Path path = filePath.resolve(fileName).normalize();

        UrlResource resource = new UrlResource(path.toUri());
        if(resource.exists()){
            return resource;
        }

        throw new RuntimeException("file " + fileName + " not found");
    }
}
